package com.juzipi.framework.web.service;



import com.juzipi.common.exception.BaseException;
import com.juzipi.common.model.Mail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * 邮箱
 */

@Service
public class MailService {

    //这个是mail的类吧，它会去读取配置文件里加的mail属性
    @Autowired
    private MailProperties mailProperties;
    @Autowired
    private JavaMailSender javaMailSender;


    //发送普通文本
    public void send(Mail mail) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(mailProperties.getUsername());
        mailMessage.setTo(mail.getEmail());
        mailMessage.setSubject(mail.getSubject());
        mailMessage.setText(mail.getContent());
        javaMailSender.send(mailMessage);
    }


    /**
     * 发送html格式的邮件，可以添加附件
     * @param mail
     * @throws Exception
     */
    public void sendHtmlAnnex(Mail mail) {
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(mailProperties.getUsername());//发送方
            helper.setTo(mail.getEmail());//接收方邮箱
            helper.setSubject(mail.getSubject());//主题
            helper.setText(mail.getContent(),true);//内容
            //添加附件
            FileSystemResource fileSystemResource = new FileSystemResource(new File(mail.getFilePath()));
            String fileName = mail.getFilePath().substring(mail.getFilePath().lastIndexOf(File.separator));
            helper.addAttachment(fileName,fileSystemResource);
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            throw new BaseException("发送邮件失败");
        }
    }


    /**
     * 发送html邮件无附件
     * @param mail
     */
    public void sendHtml(Mail mail) {
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(mailProperties.getUsername());//发送方
            helper.setTo(mail.getEmail());//接收方邮箱
            helper.setSubject(mail.getSubject());//主题
            helper.setText(mail.getContent(),true);//内容
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            throw new BaseException("发送邮件失败");
        }
    }


}
